package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Validator;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.util.SnowflakeIdUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanValidators;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;

    @Autowired
    private RedisService redisCache;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 查询非会员部门下的所有用户
     *
     * @param memberDeptId 会员部门ID
     * @return 用户列表
     */
    @Override
    public List<SysUser> selectNonMemberUsers(Long memberDeptId) {
        return userMapper.selectNonMemberUsers(memberDeptId);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验身份证号码是否唯一
     * lqx
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkIdNumberUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkIdNumberUnique(user.getIdNumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        //同步学员信息
        String idNumber = user.getIdNumber();
        String studentId = String.valueOf(new SnowflakeIdUtils(5, 8).nextId());
//        List<StudentsUser> studentsUsers= userMapper.selectStudentdByIdCard(idCard);
        StudentsUser studentsUser1 = userMapper.selectStudentsUserByIdNumber(idNumber);
        if (studentsUser1 == null) {
            //如果没有该身份证号的学员信息则新增
            StudentsUser studentsUser = new StudentsUser();
            BeanUtils.copyProperties(user, studentsUser);
            studentsUser.setUserType(user.getExampleOne());
            studentsUser.setIsTrace("0");
            studentsUser.setDelFlag("0");
            studentsUser.setStudentId(studentId);
            if (!"".equals(user.getUnitId()) && user.getUnitId() != null){
                studentsUser.setUnitId(user.getUnitId());
            }
            studentsUser.setStudentName(user.getNickName());
            if (!"".equals(user.getPositionRank()) && user.getPositionRank() != null) {
                studentsUser.setPosition(user.getPositionRank());
            }
            userMapper.insertStudents(studentsUser);
            user.setStudentId(studentId);
        } else {
            //如果有该身份证号的学员信息则更新
            //判断是否是删除状态-删除标志（0代表存在 2代表删除）
//            if ("2".equals(studentsUser1.getDelFlag())){
//                //被删除，则修改状态0,同时同步信息
//                BeanUtils.copyProperties(user,studentsUser1);
//                studentsUser1.setStudentName(user.getNickName());
//                if (!user.getPositionRank().isEmpty()){
//                    studentsUser1.setPosition(user.getPositionRank());
//                }
//                studentsUser1.setIsTrace("0");
//                studentsUser1.setDelFlag("0");
//                user.setStudentId(studentsUser1.getStudentId());
//                userMapper.updateStudents(studentsUser1);
//            }else {
            //未被删除,同时同步信息
            BeanUtils.copyProperties(user, studentsUser1);
            studentsUser1.setStudentName(user.getNickName());
            if (!"".equals(user.getPositionRank()) && user.getPositionRank() != null) {
                studentsUser1.setPosition(user.getPositionRank());
            }
            user.setStudentId(studentsUser1.getStudentId());
            userMapper.updateStudents(studentsUser1);
//            }
        }
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        SysUser sysUser = userMapper.selectUserById(user.getUserId());
        //同步学员信息
        String studentId = sysUser.getStudentId();
        //通过学员id查询学员信息
        if (studentId != null && !"".equals(studentId)) {
            StudentsUser studentsUser = userMapper.selectStudentByStudentId(studentId);
            if (studentsUser != null) {
                BeanUtils.copyProperties(user, studentsUser);
                studentsUser.setUserType(user.getExampleOne());
                studentsUser.setStudentId(studentId);
                studentsUser.setStudentName(user.getNickName());
                if (!"".equals(user.getPositionRank()) && user.getPositionRank() != null) {
                    studentsUser.setPosition(user.getPositionRank());
                }
                userMapper.updateStudents(studentsUser);
            }
        }
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUserStatus(user.getUserId(), user.getStatus());
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean updateUserProfile(SysUser user) {
        SysUser sysUser = userMapper.selectUserById(user.getUserId());
        //同步学员信息
        String studentId = sysUser.getStudentId();
        //通过学员id查询学员信息
        if (studentId != null && !"".equals(studentId)) {
            StudentsUser studentsUser = userMapper.selectStudentByStudentId(studentId);
            if (studentsUser != null) {
                BeanUtils.copyProperties(user, studentsUser);
                studentsUser.setUserType(user.getExampleOne());
                studentsUser.setStudentId(studentId);
                studentsUser.setStudentName(user.getNickName());
                if (!"".equals(user.getPositionRank()) && user.getPositionRank() != null) {
                    studentsUser.setPosition(user.getPositionRank());
                }
                userMapper.updateStudents(studentsUser);
            }
        }
        return userMapper.updateUser(user) > 0;
    }

    /**
     * 修改用户头像
     *
     * @param userId 用户ID
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        return userMapper.updateUserAvatar(userId, avatar) > 0;
    }

    /**
     * 更新用户登录信息（IP和登录时间）
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean updateLoginInfo(SysUser user) {
        return userMapper.updateLoginInfo(user) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.resetUserPwd(user.getUserId(), user.getPassword());
    }

    /**
     * 重置用户密码
     *
     * @param userId   用户ID
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(Long userId, String password) {
        return userMapper.resetUserPwd(userId, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
            //同步删除学员
            SysUser sysUser = userMapper.selectUserById(userId);
            if (sysUser.getStudentId() != null && !"".equals(sysUser.getStudentId())) {
                StudentsUser studentsUser = new StudentsUser();
                studentsUser.setStudentId(sysUser.getStudentId());
                studentsUser.setDelFlag("2");
                studentsUser.setIsTrace("2");
                userMapper.updateStudents(studentsUser);
            }
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setDeptId(u.getDeptId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 手机注册
     */
    @Override
    public String register(PhoneRegisterBody registerBody) {
        //设置默认的账号密码，规则为 youke2025916
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        String phonenumber = registerBody.getPhonenumber();
        sysUser.setPhonenumber(phonenumber);
        String check = codeCheck(phonenumber, registerBody.getCode());

        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (!check.equals("success")) {
            msg = check;
        } else if (!checkPhoneUnique(sysUser)) {
            msg = "该手机号已被注册";
        } else {
            redisCache.deleteObject(phonenumber);
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                //AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    @Override
    public SysUser selectUserByPhonenNmber(String phonenumber) {
        return userMapper.selectUserByPhonenNmber(phonenumber);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean registerPhoneUser(PhoneRegisterBody phoneRegisterBody) {
        System.out.println("进入registerPhoneUser");
        boolean regFlag = true;
        String msg = "";
        String username = phoneRegisterBody.getUsername();
        String password = phoneRegisterBody.getPassword();
        SysUser sysUser = new SysUser();
        //设置账号
        sysUser.setUserName(phoneRegisterBody.getUserName());
//        sysUser.setNickName(username);
        //设置昵称
        sysUser.setNickName(phoneRegisterBody.getNickName());
        //设置电话
        String phonenumber = phoneRegisterBody.getPhonenumber();
        sysUser.setPhonenumber(phonenumber);
        //设置人员类型
        sysUser.setExampleOne(phoneRegisterBody.getExampleOne());
        //检查验证码
        String check = codeCheck(phonenumber + phoneRegisterBody.getUuid(), phoneRegisterBody.getCode());
        if (!check.equals("success")) {
            System.out.println("验证码检查不通过");
            redisCache.deleteObject(phonenumber + phoneRegisterBody.getUuid());
            return false;
        }
        System.out.println("验证码检查通过");
        redisCache.deleteObject(phonenumber + phoneRegisterBody.getUuid());
//        sysUser.setNickName(username);
        //设置密码
        sysUser.setPassword(SecurityUtils.encryptPassword(password));

        //判断是否有填单位
        if (!"".equals(phoneRegisterBody.getSocialCreditCode()) && phoneRegisterBody.getSocialCreditCode() != null){
            System.out.println("进入判断是否有填单位");
            //判断该单位是否存在
            Units units = userMapper.selectUnitBySocialCreditCode(phoneRegisterBody.getSocialCreditCode());
            if (units != null){
                //存在，设置单位id
                sysUser.setUnitId(units.getUnitId());
            }else {
                //不存在，新增单位
                Units units1 = new Units();
                //赋值
                units1.setUnitId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                units1.setCreateTime(DateUtils.getNowDate());
                units1.setUnitName(phoneRegisterBody.getUnitName());
                units1.setSocialCreditCode(phoneRegisterBody.getSocialCreditCode());
                //设置单位id
                sysUser.setUnitId(units1.getUnitId());
                userMapper.insertUnits(units1);
            }
        }

        //同步学员信息
        String idNumber = sysUser.getIdNumber();
        String studentId = String.valueOf(new SnowflakeIdUtils(5, 8).nextId());
        StudentsUser studentsUser1 = userMapper.selectStudentsUserByIdNumber(idNumber);
        if (studentsUser1 == null) {
            //如果没有该身份证号的学员信息则新增
            StudentsUser studentsUser = new StudentsUser();
            BeanUtils.copyProperties(sysUser, studentsUser);
            studentsUser.setUserType(sysUser.getExampleOne());
            studentsUser.setIsTrace("0");
            studentsUser.setDelFlag("0");
            studentsUser.setStudentId(studentId);
            if (!"".equals(sysUser.getUnitId()) && sysUser.getUnitId() != null){
                studentsUser.setUnitId(sysUser.getUnitId());
            }
            studentsUser.setStudentName(sysUser.getNickName());
            if (!"".equals(sysUser.getPositionRank()) && sysUser.getPositionRank() != null) {
                studentsUser.setPosition(sysUser.getPositionRank());
            }
            userMapper.insertStudents(studentsUser);
            sysUser.setStudentId(studentId);
        } else {
            //如果有该身份证号的学员信息则更新
            //判断是否是删除状态-删除标志（0代表存在 2代表删除）
            //未被删除,同时同步信息
            BeanUtils.copyProperties(sysUser, studentsUser1);
            studentsUser1.setStudentName(sysUser.getNickName());
            if (!"".equals(sysUser.getPositionRank()) && sysUser.getPositionRank() != null) {
                studentsUser1.setPosition(sysUser.getPositionRank());
            }
            sysUser.setStudentId(studentsUser1.getStudentId());
            userMapper.updateStudents(studentsUser1);
        }
        //注册用户
        regFlag = registerUser(sysUser);
//        if (regFlag) {
//            //注册成功，同步学员信息
//            Long userId = sysUser.getUserId();
//            phoneRegisterBody.setUserId(userId);
//            int i = userMapper.registerPhoneUser(phoneRegisterBody);
//            List<StudentsUser> studentsUsers = userMapper.selectStudentdByIdCard(phoneRegisterBody.getIdNumber());
//            if (studentsUsers.isEmpty()) {
//                StudentsUser studentsUser = new StudentsUser();
//                BeanUtils.copyProperties(phoneRegisterBody, studentsUser);
//                studentsUser.setStudentId(String.valueOf(new SnowflakeIdUtils(5, 8).nextId()));
//                studentsUser.setStudentName(phoneRegisterBody.getUserName());
//                userMapper.insertStudents(studentsUser);
//            }
//            if (i > 0) {
//                regFlag = true;
//            } else {
//                regFlag = false;
//            }
//        }
        return regFlag;
    }

    /**
     * 验证码校验
     *
     * @param phonenumber 手机号
     * @param code        验证码
     * @return
     */
    public String codeCheck(String phonenumber, String code) {
        Boolean bool = redisCache.hasKey(phonenumber);
        if (bool != null && bool) {
            String redisCode = redisCache.getCacheObject(phonenumber);
            if (redisCode.equals(code)) {
                return "success";
            } else {
                return "验证码不匹配";
            }
        } else {
            return "验证码已过期";
        }
    }
}
